package cn.yunhe.servlet;

import cn.yunhe.entity.Product;
import cn.yunhe.service.ProductService;
import cn.yunhe.util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/GetProListByName")
public class GetProListByName extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String keyword = request.getParameter("keyword");
        if(keyword == null || keyword.trim().equals("")){
            keyword = "";
        }
        ProductService ps = new ProductService();
        String currPage = request.getParameter("pageIndex");
        if (currPage == null) {
            currPage = "1";
        }
        int pageIndex=Integer.parseInt(currPage);
        int totalDatas=ps.getProCount();
        int totalPages=PageUtil.getTotalPages(totalDatas);
        if (pageIndex < 1) {
            pageIndex = 1;
        }
        if (pageIndex > totalPages) {
            pageIndex = totalPages;
        }


        List<Product> list = ps.getAllByName(pageIndex, keyword);
        request.setAttribute("keyword",keyword);
        request.setAttribute("pageIndex",pageIndex);
        request.setAttribute("productList",list);
        request.setAttribute("totalPages",totalPages);
        request.getRequestDispatcher("product-list.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
